//
//  Manager.m
//  diaoyuren
//
//  Created by 钓鱼人 on 15/12/19.
//  Copyright © 2015年 game. All rights reserved.
//

#import "Manager.h"
#import "AFNetworking.h"
#import "PramasMontage.h"
#import "CGFdbmBase.h"
#import "ShoolDataModel.h"
#import "MJRefresh.h"
#import "MBProgressHUD.h"
#import <CommonCrypto/CommonCrypto.h>
#import <CommonCrypto/CommonDigest.h>
#import <Security/Security.h>
#import "GTMBase64.h"
#import "FMDB.h"
#import "FMDatabase.h"
#import "CityModel.h"
#import "MainPageModel.h"
#import <sys/sysctl.h>
#import <mach/mach.h>
#define PI 3.14159265358979323846264338327950288

//#define ORIGINAL_MAX_WIDTH 100.0f
@interface Manager()
@end
@implementation Manager
+(instancetype)sharedManager{
    static Manager *instance  =nil;
    static dispatch_once_t oneceToken;
    
    dispatch_once(&oneceToken, ^{
        instance = [[Manager alloc]init];
    });
    return instance;
}

-(instancetype)init{
    if (self = [super init]) {
        
    }
    return self;

}

//产生8位随机字符串
+(NSString *)ret8bitString

{
    
    char data[8];
    
    for (int x=0;x<8;data[x++] = (char)('A' + (arc4random_uniform(26))));
    
    return [[NSString alloc] initWithBytes:data length:8 encoding:NSUTF8StringEncoding];
    
}



/**
 *  textFile左边视图  放大镜
 */
+(UIView *)textFileLweftView{
    UIView *bacView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, 30, 30)];
    
    UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"btn-search-grey"]];
    imageView.frame = CGRectMake(8,5,W(bacView)-10,W(bacView)-10);
    [bacView addSubview:imageView];
    
    return bacView;
}


// 获取当前设备可用内存(单位：MB）
- (double)availableMemory{
    
    vm_statistics_data_t vmStats;
    mach_msg_type_number_t infoCount = HOST_VM_INFO_COUNT;
    kern_return_t kernReturn = host_statistics(mach_host_self(),
                                               HOST_VM_INFO,
                                               (host_info_t)&vmStats,
                                               &infoCount);
    if (kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    return ((vm_page_size *vmStats.free_count) / 1024.0) / 1024.0;
}

// 获取当前任务所占用的内存（单位：MB）
- (double)usedMemory{
    
    task_basic_info_data_t taskInfo;
    mach_msg_type_number_t infoCount = TASK_BASIC_INFO_COUNT;
    kern_return_t kernReturn = task_info(mach_task_self(),
                                         TASK_BASIC_INFO,
                                         (task_info_t)&taskInfo,
                                         &infoCount);
    if (kernReturn != KERN_SUCCESS) {
        return NSNotFound;
    }
    return taskInfo.resident_size / 1024.0 / 1024.0;
}


/**
 *  天气的城市，本地数组
 */
+(NSString *)CityAryPath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [NSString stringWithFormat:@"%@/Library/Caches/Weath",NSHomeDirectory()];;
    
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];//在路径创建文件夹
    NSString *filePath = [NSString stringWithFormat:@"%@/Weath.plist",path];
    return filePath;
}

//草稿箱存储地址
+(NSString *)editeFilePath{
    
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [NSString stringWithFormat:@"%@/Library/Caches/editCaches",NSHomeDirectory()];;
    
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];//在路径创建文件夹
    
    return [NSString stringWithFormat:@"%@/editeAry.plist",path];
    
}

/**
 *  压缩图片 指定尺寸
 *
 */
+(UIImage *) imageCompressForSize:(UIImage *)sourceImage targetSize:(CGSize)size{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = size.width;
    CGFloat targetHeight = size.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    
    UIGraphicsBeginImageContext(size);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    [sourceImage drawInRect:thumbnailRect];
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}
/**
 *
 *  压缩图片  指定宽度 然后按原图比例压缩
 */
+(UIImage *) imageCompressForWidth:(UIImage *)sourceImage targetWidth:(CGFloat)defineWidth
{
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = defineWidth;
    CGFloat targetHeight = height / (width / targetWidth);
    CGSize size = CGSizeMake(targetWidth, targetHeight);
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0, 0.0);
    if(CGSizeEqualToSize(imageSize, size) == NO){
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        if(widthFactor > heightFactor){
            scaleFactor = widthFactor;
        }
        else{
            scaleFactor = heightFactor;
        }
        scaledWidth = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        if(widthFactor > heightFactor){
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }else if(widthFactor < heightFactor){
            thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
        }
    }
    UIGraphicsBeginImageContext(size);
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil){
        NSLog(@"scale image fail");
    }
    UIGraphicsEndImageContext();
    return newImage;
}


+(NSString *)AchiveNowTime{
    
    NSDate *  senddate=[NSDate date];
    
    NSDateFormatter  *dateformatter=[[NSDateFormatter alloc] init];
    
    [dateformatter setDateFormat:@"MM-dd HH:mm"];
    
   return  [dateformatter stringFromDate:senddate];
}

/**
 *  计算 textView 内容的高度
 */
+(CGFloat )textViewCounthight:(UITextView *)textView{
    
    CGRect textViewFrame = textView.frame;
    CGSize textSize = [textView sizeThatFits:CGSizeMake(CGRectGetWidth(textViewFrame), 1000.0f)];
    textViewFrame.size.height = textSize.height;
    textView.frame = textViewFrame;
    return textViewFrame.size.height;
}

-(NSString *)WithCityCreatPath{
    NSFileManager *fileManager = [NSFileManager defaultManager];
    NSString *path = [NSString stringWithFormat:@"%@/Library/Caches/Weath",NSHomeDirectory()];;
    
    [fileManager createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];//在路径创建文件夹
    NSString *filePath = [NSString stringWithFormat:@"%@/Weath.plist",path];
    return filePath;
}

+(NSDictionary *)WeathcityFromSQl:(NSString *)cityname{
    
    if ([cityname isEqualToString:@"巴音郭..."]) {
        cityname  = @"巴音郭楞";
    }

    NSString *selectString= [NSString stringWithFormat:@"SELECT * FROM region_city WHERE short_name = '%@'",cityname];
    return [CGFdbmBase SearchSelfPathSqlWhithPath:@"diaoyur_city" AndTabName:@"region_city" SelectSting:selectString].firstObject;
}


/**
 *  通过城市名称获取城市经纬度以及拼音
 *
 *  @param cityName       城市名字
 *  @param isNotificayion 是否 通知 钓场 城市已经跟换，需要重新加载数据
 */
+(void)CityLocalAndPinYFromSQlWhithCityName:(NSString *)cityName AndIsNotificayion:(BOOL)isNotificayion{
    
    
    if ([cityName isEqualToString:@"巴音郭..."]) {
        cityName  = @"巴音郭楞";
    }
    
    NSUserDefaults *Myud = [NSUserDefaults standardUserDefaults];
    
    [Myud removeObjectForKey:@"localName"];
    
    [Myud setValue:cityName forKey:@"localName"];
    
    
    CityModel  *cityModel = [[CityModel alloc]initWithDictionary:[Manager WeathcityFromSQl:[Myud valueForKey:@"localName"]] error:nil];

    
    NSArray *latitude = [cityModel.location componentsSeparatedByString:@","];
    
    if ([Myud valueForKey:@"Locallongitude"]==nil&&[Myud valueForKey:@"Locallatitude"]==nil) {
        
        [Myud setValue:latitude[0] forKey:@"longitude"];
        [Myud setValue:latitude[1] forKey:@"latitude"];
    }
    
    
    [Myud setValue:cityModel.pinyin forKey:@"cityPinY"];
    [Myud setValue:cityModel.code forKey:@"Citycode"];
    [Myud setValue:[Manager WeathcityFromSQl:cityName] forKey:@"CityDic"];
        
    if (isNotificayion) {
        [[NSNotificationCenter defaultCenter]postNotificationName:@"CityChange" object:self];
    }
}

#pragma mark camera utility
+ (BOOL) isCameraAvailable{//判断设备是否有摄像头
    return [UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera];
}

// 后面的摄像头是否可用
+ (BOOL) isRearCameraAvailable{
    return [UIImagePickerController isCameraDeviceAvailable:UIImagePickerControllerCameraDeviceRear];
}

// 检查摄像头是否支持拍照
+ (BOOL) doesCameraSupportTakingPhotos {
    return [Manager cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypeCamera];
}

// 相册是否可用
+ (BOOL) isPhotoLibraryAvailable{
    return [UIImagePickerController isSourceTypeAvailable:
            UIImagePickerControllerSourceTypePhotoLibrary];
}

// 是否可以在相册中选择视频
+ (BOOL) canUserPickVideosFromPhotoLibrary{
    return [Manager
            cameraSupportsMedia:(__bridge NSString *)kUTTypeMovie sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

// 是否可以在相册中选择视频
+ (BOOL) canUserPickPhotosFromPhotoLibrary{
    return [Manager
            cameraSupportsMedia:(__bridge NSString *)kUTTypeImage sourceType:UIImagePickerControllerSourceTypePhotoLibrary];
}

// 判断是否支持某种多媒体类型：拍照，视频
+ (BOOL) cameraSupportsMedia:(NSString *)paramMediaType sourceType:(UIImagePickerControllerSourceType)paramSourceType{
    __block BOOL result = NO;
    if ([paramMediaType length] == 0) {
        return NO;
    }
    NSArray *availableMediaTypes = [UIImagePickerController availableMediaTypesForSourceType:paramSourceType];
    [availableMediaTypes enumerateObjectsUsingBlock: ^(id obj, NSUInteger idx, BOOL *stop) {
        NSString *mediaType = (NSString *)obj;
        if ([mediaType isEqualToString:paramMediaType]){
            result = YES;
            *stop= YES;
        }
    }];
    return result;
}


#pragma mark----将图片旋转到竖屏样子  因为相册相片如果是前摄像头或者是竖屏拍摄 虽然显示出来是正常显示(我们想要的样子)实际上图片的方向还是是处于拍摄时的方向  所以要将其处理到真正的竖屏状态
+ (UIImage *)fixOrientation:(UIImage *)aImage {
    
    // No-op if the orientation is already correct
    if (aImage.imageOrientation == UIImageOrientationUp)
        return aImage;
    
    // We need to calculate the proper transformation to make the image upright.
    // We do it in 2 steps: Rotate if Left/Right/Down, and then flip if Mirrored.
    CGAffineTransform transform = CGAffineTransformIdentity;
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationDown:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, aImage.size.height);
            transform = CGAffineTransformRotate(transform, M_PI);
            break;
            
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformRotate(transform, M_PI_2);
            break;
            
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, 0, aImage.size.height);
            transform = CGAffineTransformRotate(transform, -M_PI_2);
            break;
        default:
            break;
    }
    
    switch (aImage.imageOrientation) {
        case UIImageOrientationUpMirrored:
        case UIImageOrientationDownMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.width, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
            
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRightMirrored:
            transform = CGAffineTransformTranslate(transform, aImage.size.height, 0);
            transform = CGAffineTransformScale(transform, -1, 1);
            break;
        default:
            break;
    }
    
    // Now we draw the underlying CGImage into a new context, applying the transform
    // calculated above.
    CGContextRef ctx = CGBitmapContextCreate(NULL, aImage.size.width, aImage.size.height,
                                             CGImageGetBitsPerComponent(aImage.CGImage), 0,
                                             CGImageGetColorSpace(aImage.CGImage),
                                             CGImageGetBitmapInfo(aImage.CGImage));
    CGContextConcatCTM(ctx, transform);
    switch (aImage.imageOrientation) {
        case UIImageOrientationLeft:
        case UIImageOrientationLeftMirrored:
        case UIImageOrientationRight:
        case UIImageOrientationRightMirrored:
            // Grr...
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.height,aImage.size.width), aImage.CGImage);
            break;
            
        default:
            CGContextDrawImage(ctx, CGRectMake(0,0,aImage.size.width,aImage.size.height), aImage.CGImage);
            break;
    }
    
    // And now we just create a new UIImage from the drawing context
    CGImageRef cgimg = CGBitmapContextCreateImage(ctx);
    UIImage *img = [UIImage imageWithCGImage:cgimg];
    CGContextRelease(ctx);
    CGImageRelease(cgimg);
    return img;
}


//计算字体高度
+(CGFloat )CountTextWhithSize:(CGSize)size AndString:(NSString *)str AndfFontSize:(CGFloat)X{
    
    CGRect Myrect = [str boundingRectWithSize:size options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:[UIFont fontWithName:@"AvenirNext-Regular" size:X], NSFontAttributeName,nil] context:nil];
    return Myrect.size.height;
}


#pragma mark--图片旋转
+(UIImageView *) makeRotation:(UIImageView *)image speedX:(float)X speedY:(float)Y
{
    //    #define PI 3.14159265358979323846264338327950288
    if (Y<0) {
        image.transform = CGAffineTransformMakeRotation(atan(X/(-Y)));
    }else if(Y>0){
        image.transform = CGAffineTransformMakeRotation(atanf(X/(-Y))-PI);
    }
    return image;
}


//字符串解密
+(NSString*)doDecEncryptStr:(NSString *)encryptStr withKey:(NSString*)key{
    
    if (key.length<24) {
        NSInteger cout = 24-key.length;
        for (int i = 0; i<cout; i++) {
            key = [key stringByAppendingString:@"0"];
        }
    }
    
    NSData *encryptData = [GTMBase64 decodeData:[encryptStr dataUsingEncoding:NSUTF8StringEncoding]];
    size_t plainTextBufferSize = [encryptData length];
    const void *vplainText = [encryptData bytes];
    CCCryptorStatus ccStatus;
  __block uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
    const void *vkey = (const void *) [key UTF8String];
    const void *vinitVec = nil;//(const void *) [gIv UTF8String];
    ccStatus = CCCrypt(kCCDecrypt,
                       kCCAlgorithm3DES,
                       kCCOptionPKCS7Padding|kCCOptionECBMode,
                       vkey,
                       kCCKeySize3DES,
                       vinitVec,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    NSString *result = [[NSString alloc] initWithData:[NSData dataWithBytes:(const void *)bufferPtr
                                                                     length:(NSUInteger)movedBytes] encoding:NSUTF8StringEncoding];
    return result;
}

//字符串加密
+ (NSString*)doEncryptStr:(NSString*)plainText withKey:(NSString*)key{
    
    //补零操作 key不足24位用0补满
    if (key.length<24) {
        NSInteger cout = 24-key.length;
        for (int i = 0; i<cout; i++) {
            key = [key stringByAppendingString:@"0"];
        }
    }
    
    NSData* data = [plainText dataUsingEncoding:NSUTF8StringEncoding];
    size_t plainTextBufferSize = [data length];
    const void *vplainText = (const void *)[data bytes];
    CCCryptorStatus ccStatus;
   __block uint8_t *bufferPtr = NULL;
    size_t bufferPtrSize = 0;
    size_t movedBytes = 0;
    
    bufferPtrSize = (plainTextBufferSize + kCCBlockSize3DES) & ~(kCCBlockSize3DES - 1);
    bufferPtr = malloc( bufferPtrSize * sizeof(uint8_t));//造成内存泄漏
    memset((void *)bufferPtr, 0x0, bufferPtrSize);
    
    const void *vkey = (const void *)[key UTF8String];// keyByte;
    const void *vinitVec = nil;//(const void *) [gIv UTF8String];
    
    ccStatus = CCCrypt(kCCEncrypt,
                       kCCAlgorithm3DES,
                       kCCOptionECBMode|kCCOptionPKCS7Padding,
                       vkey,
                       kCCKeySize3DES,
                       vinitVec,
                       vplainText,
                       plainTextBufferSize,
                       (void *)bufferPtr,
                       bufferPtrSize,
                       &movedBytes);
    
    NSData *myData = [NSData dataWithBytes:(const void *)bufferPtr length:(NSUInteger)movedBytes];
    NSString *result = [GTMBase64 stringByEncodingData:myData];
    return result;
}


//时间转化
+(NSString *)GetTimeWhithTimesMark:(NSInteger )timesp{
    NSString *timeS;
    
    NSTimeInterval val = [[NSDate date] timeIntervalSince1970];
    
    CGFloat time = val-timesp;
    
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:timesp];
//    NSTimeInterval time = [[NSDate date] timeIntervalSinceDate:date];
    CGFloat day=time/(3600*24);
    CGFloat hour = time/3600;
    CGFloat min = time/60;
    
    if (day>5) {
        //substringToIndex 截取index位置前的字符串，后面的都不要
        timeS = [[NSString stringWithFormat:@"%@",date] substringToIndex:10];
    }else if (day>1) {
        timeS=[NSString stringWithFormat:@"%.0f天前",day];
    }else if (hour>1) {
        timeS=[NSString stringWithFormat:@"%.0f小时前",hour];
        
    }else if (min>1){
        timeS=[NSString stringWithFormat:@"%.0f分钟前",min];
        
    }else{
        timeS=@"刚刚";
    }
    return timeS;
}

/*!
 * @brief 把格式化的JSON格式的字符串转换成字典
 * @param jsonString JSON格式的字符串
 * @return 返回字典
 */
+(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString{
    if (jsonString == nil) {
        return nil;
    }
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                        error:&err];
    if(err) {
       
        return nil;
    }
    return dic;
}

+(void)GetHudWhithText:(NSString *)text AndFatherView:(UIView *)fatherView{

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:fatherView animated:YES];
    hud.mode = MBProgressHUDModeText;
    hud.detailsLabelText = text;
    hud.detailsLabelFont = [UIFont systemFontOfSize:SCREEN_WIDTH*0.05];
    hud.labelColor=[UIColor whiteColor];
    hud.color=[UIColor blackColor];
//     hud.labelFont = [UIFont systemFontOfSize:13];
    hud.removeFromSuperViewOnHide = YES;
    [hud show:YES];
    [hud hide:YES afterDelay:1];
}

#pragma mark image scale utility --压缩图片
+ (UIImage *)imageByScalingToMaxSize:(UIImage *)sourceImage WhithMAXWIdth:(CGFloat )width{
    if (sourceImage.size.width < width) return sourceImage;
    CGFloat btWidth = 0.0f;
    CGFloat btHeight = 0.0f;
    if (sourceImage.size.width > sourceImage.size.height) {
        btHeight = width;
        btWidth = sourceImage.size.width * (width / sourceImage.size.height);
    } else {
        btWidth = width;
        btHeight = sourceImage.size.height * (width / sourceImage.size.width);
    }
    CGSize targetSize = CGSizeMake(btWidth, btHeight);
    return [self imageByScalingAndCroppingForSourceImage:sourceImage targetSize:targetSize];
}

+ (UIImage *)imageByScalingAndCroppingForSourceImage:(UIImage *)sourceImage targetSize:(CGSize)targetSize {
    UIImage *newImage = nil;
    CGSize imageSize = sourceImage.size;
    CGFloat width = imageSize.width;
    CGFloat height = imageSize.height;
    CGFloat targetWidth = targetSize.width;
    CGFloat targetHeight = targetSize.height;
    CGFloat scaleFactor = 0.0;
    CGFloat scaledWidth = targetWidth;
    CGFloat scaledHeight = targetHeight;
    CGPoint thumbnailPoint = CGPointMake(0.0,0.0);
    if (CGSizeEqualToSize(imageSize, targetSize) == NO)
    {
        CGFloat widthFactor = targetWidth / width;
        CGFloat heightFactor = targetHeight / height;
        
        if (widthFactor > heightFactor)
            scaleFactor = widthFactor; // scale to fit height
        else
            scaleFactor = heightFactor; // scale to fit width
        scaledWidth  = width * scaleFactor;
        scaledHeight = height * scaleFactor;
        
        // center the image
        if (widthFactor > heightFactor)
        {
            thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5;
        }
        else
            if (widthFactor < heightFactor)
            {
                thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5;
            }
    }
    UIGraphicsBeginImageContext(targetSize); // this will crop
    CGRect thumbnailRect = CGRectZero;
    thumbnailRect.origin = thumbnailPoint;
    thumbnailRect.size.width  = scaledWidth;
    thumbnailRect.size.height = scaledHeight;
    
    [sourceImage drawInRect:thumbnailRect];
    
    newImage = UIGraphicsGetImageFromCurrentImageContext();
    if(newImage == nil)
    
    //pop the context to get back to the default
    UIGraphicsEndImageContext();
    return newImage;
}

#pragma mark---对城市数组进行拼音转化
- (void)CityNameToPingYinCityAry:(NSArray *)cityAry Result:(ListAndComent)result{
    NSString *str = @"";
    for (int i = 0;i<cityAry.count;i++) {
        
        str = [str stringByAppendingString:[NSString stringWithFormat:@"\t%@",cityAry[i]]];
    }
    
    NSMutableDictionary *dic = [NSMutableDictionary dictionary];
    NSMutableString *muStr = [NSMutableString string];
    
    for (int i=0; i<str.length; i++) {
        NSString *subStr = [str substringWithRange:NSMakeRange(i, 1)];
        if ([subStr isEqualToString:@"\t"]) {
            muStr = [NSMutableString string];
        } else {
            [muStr appendString:subStr];
            NSString *muSubStr = nil;
            if ((i+1) < str.length) {
                muSubStr = [str substringWithRange:NSMakeRange(i+1, 1)];
            }
            if ([muSubStr isEqualToString:@"\t"] || (i+1) > str.length) {
                //转成了可变字符串
                NSMutableString *strC = [NSMutableString stringWithString:muStr];
                //先转换为带声调的拼音
                CFStringTransform((CFMutableStringRef)strC,NULL, kCFStringTransformMandarinLatin,NO);
                //再转换为不带声调的拼音
                CFStringTransform((CFMutableStringRef)strC,NULL, kCFStringTransformStripDiacritics,NO);
                //转化为大写拼音
                NSString *pinYin = [strC capitalizedString];
                NSString *captalStr = [pinYin substringToIndex:1];
                NSArray *allKey = [dic allKeys];
                BOOL hasKey = false;
                for (int j=0; j<[allKey count]; j++) {
                    if ([captalStr isEqualToString:allKey[j]]) {
                        hasKey = true;
                        [[dic objectForKey:captalStr] addObject:muStr];
                        break;
                    }
                }
                if (!hasKey) {
                    NSMutableArray *muAry = [NSMutableArray array];
                    [muAry addObject:muStr];
                    [dic setObject:muAry forKey:captalStr];
                }
            }
        }
    }
    NSArray *allKeys = [dic allKeys];
    NSMutableArray *keyAscend = [NSMutableArray array];
    for (int n=0; n<[allKeys count]; n++) {
        BOOL hasInserted = false;
        for (int m=0; m<[keyAscend count]; m++) {
            if ([keyAscend[m] compare:allKeys[n]] > 0) {
                hasInserted = true;
                [keyAscend insertObject:allKeys[n] atIndex:m];
                break;
            }
        }
        if (!hasInserted) {
            [keyAscend addObject:allKeys[n]];
        }
    }
  NSArray  *headerAry = [NSArray arrayWithArray:keyAscend];
    NSMutableArray *dataMut = [NSMutableArray array];
    for (int j=0; j<[headerAry count]; j++) {
        [dataMut addObject:[dic objectForKey:headerAry[j]]];
    }
   NSArray *dataAry = [NSArray arrayWithArray:dataMut];
//    NSDictionary *dataDic = [NSDictionary dictionaryWithObjects:dataAry forKeys:headerAry];
    result(headerAry,dataAry,nil,nil);
}

#pragma mark---获取城市列表数据
-(void)CityDataFromSQL:(CityBlock)CityBlock{
    
    NSString *dbPath = [[NSBundle mainBundle]pathForResource:@"diaoyur_city" ofType:@"db"];
    NSFileManager *manager = [NSFileManager defaultManager];
    
    NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentPath = [path.firstObject stringByAppendingPathComponent:@"diaoyur_city.db"];
    
    [manager copyItemAtPath:dbPath toPath:documentPath error:nil];
    
    FMDatabase *dbDatabase = [FMDatabase databaseWithPath:documentPath];
    
    [dbDatabase open];
    NSString *quer = @"SELECT * FROM region_city";
    
    NSMutableArray *ModelAry = [NSMutableArray array];
    NSMutableArray *cityArt = [NSMutableArray array];
    [dbDatabase executeStatements:quer withResultBlock:^int(NSDictionary *resultsDictionary) {
        
        CityModel *model = [[CityModel alloc]initWithDictionary:resultsDictionary error:nil];
       
        [ModelAry addObject:model];
        [cityArt addObject:model.short_name];
        return 0;
    }];
        CityBlock(ModelAry,cityArt);
    
    [dbDatabase close];
}


-(void)ResponseWhithURL:(NSString *)url AndParameter:(NSDictionary *)params AndCompletionType:(CompletionType)completion{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
     manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",nil];
    
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager POST:url parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        
        completion(responseObject,nil);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        
        DIEError *err = [[DIEError alloc]initWithError:error];
        completion(nil,err);
        
       
    }];
}

-(void)RequestWhithURL:(NSString *)url AndParameter:(NSDictionary *)params AndCompletionType:(CompletionType)completion{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",nil];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager GET:url parameters:params success:^(NSURLSessionDataTask *task, id responseObject) {
        
        completion(responseObject,nil);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

        DIEError *err = [[DIEError alloc]initWithError:error];
        completion(nil,err);
    }];
}

#pragma mark--首页每日精选数据
-(void)AchiveMainpageSectionDataWhithCompletionType:(CompletionType)comple ToSQL:(ToSQL)toSQL{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript", @"text/html",nil];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    [manager GET:MainPageUrl parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        MainPageModel *model = [[MainPageModel alloc]initWithDictionary:responseObject[@"data"] error:nil];
        
        //数据库存储
        [CGFdbmBase CreatTableWhithPath:@"Main.db" TableName:@"Main" DicName:@"data" IdstrName:@"myId"];
        //只要请求成功 就清空数据库 同时将新数据存入数据库
        if ([CGFdbmBase eraseTable:@"Main"]) {
            
            [CGFdbmBase IntoDicTableName:@"Main" DicName:@"data" IdstrName:@"myId" Dic:responseObject[@"data"] idStr:@"page0"];
        }
        
        comple(model,nil);//传值
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
       toSQL();
   
      
    }];
}

#pragma mark--首页标签数据
-(void)AchiveMainPageDataWhithToSQl:(ToSQL)toSQL{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager GET:MaiCharart parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
        
        NSString *table = @"FirstPage";
        NSString *dicName = @"Dic";
        NSString *idStrName = @"idStr";
        
        NSString *Str = responseObject[@"data"][@"config_version"];
        NSDictionary *dic = responseObject[@"data"];
        
        [CGFdbmBase CreatTableWhithPath:@"FirstPage.db" TableName:table DicName:dicName IdstrName:idStrName];
        
        NSInteger TableCount = [CGFdbmBase getTableItemCount:table];
        
        if (TableCount!=0) {//判断数据库是否有数据
            NSString *SeachStr = [CGFdbmBase SeachWhithTableName:table IdStrName:idStrName];
            
            if (![SeachStr isEqualToString:Str]) {
                if ([CGFdbmBase eraseTable:@"FirstPage"]) {//如果删除成功，存新数据
                    [CGFdbmBase IntoDicTableName:table DicName:dicName IdstrName:idStrName Dic:dic idStr:Str];
                    
                    toSQL();
           
                }
            }
           
        }else{//数据库没有数据  直接添加数据-->从数据库获取数据
            
            [CGFdbmBase IntoDicTableName:table DicName:dicName IdstrName:idStrName Dic:dic idStr:Str];
                toSQL();
        }
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {

    }];
}

//学堂首页数据
-(void)AchiveDataOfSchoolTypeid:(NSInteger )typeid Page:(NSInteger )page SQLTablePath:(NSString *)path tableName:(NSString *)table AndDataAry:(NSMutableArray *)dataAry AndResult:(ListAndComent)listAndRecomment AError:(GetError )getError{
    
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
     NSDictionary *parameter = [PramasMontage fullParams:nil];
    
//    NSLog(@"%@",[PramasMontage SchoolMianPageApi:typeid Page:page]);
    
    [manager GET:[PramasMontage SchoolMianPageApi:typeid Page:page] parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        
        if (page==1) {
            [CGFdbmBase CreatTableWhithPath:path TableName:table DicName:@"data" IdstrName:@"myId"];
            //只要请求成功 就清空数据库 同时将新数据存入数据库
            if ([CGFdbmBase eraseTable:table]) {
                
                [CGFdbmBase IntoDicTableName:table DicName:@"data" IdstrName:@"myId" Dic:responseObject[@"data"] idStr:@"page0"];
            }
        }
        [dataAry addObject:responseObject[@"data"]];
        
        
        if (page!=0&&dataAry.count>=page) {
            ShoolDataModel  *model = [[ShoolDataModel alloc]initWithDictionary:dataAry[page-1] error:nil];
            NSMutableArray *recomAry = [NSMutableArray array];
            NSMutableArray *listAry = [NSMutableArray array];
            
            if (responseObject[@"data"][@"recommend"]!=nil) {
                [recomAry addObjectsFromArray:model.recommend];
            }
            
            [listAry addObjectsFromArray:model.article_list];
            listAndRecomment(listAry,recomAry,model.page_info,nil);
        }
    
        
     
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DIEError *err = [[DIEError alloc]initWithError:error];
        getError(err);

    }];
}

//大标签+小标签数据请求 请求的Url不同 返回数据大标签有recommend  小标签没有 不需要保存数据库
-(void)AchiveBigAndSmallCharectWhithUrl:(NSString *)url AndResult:(ListAndComent)listAndRecomment AError:(GetError )getError{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    NSDictionary *parameter = [PramasMontage fullParams:nil];
    [manager GET:url parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        
        ShoolDataModel  *model = [[ShoolDataModel alloc]initWithDictionary:responseObject[@"data"]error:nil];
        
        NSMutableArray *recomAry = [NSMutableArray array];
        NSMutableArray *listAry = [NSMutableArray array];
        
        if (responseObject[@"data"][@"recommend"]!=nil) {
            [recomAry addObjectsFromArray:model.recommend];
        }
        
        [listAry addObjectsFromArray:model.article_list];
        
        listAndRecomment(listAry,recomAry,model.page_info,model.fourth_classify);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        DIEError *err = [[DIEError alloc]initWithError:error];
        getError(err);
        
    }];
}

//标签数据
-(void)AchiveCharactWhithTypeid:(NSInteger )typeid AndTablePath:(NSString *)tabelPath TableName:(NSString *)tableName AndResult:(CharctAry)CharctResult Error:(GetError)getError{

    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        NSDictionary *parameter = [PramasMontage fullParams:nil];
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 30.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    [manager GET:[PramasMontage Charact:typeid] parameters:parameter success:^(NSURLSessionDataTask *task, id responseObject) {
        
        [CGFdbmBase CreatTableWhithPath:tabelPath TableName:tableName DicName:@"data" IdstrName:@"myId"];
        //只要请求成功 就清空数据库 同时将新数据存入数据库
        if ([CGFdbmBase eraseTable:tableName]) {
            
            [CGFdbmBase IntoDicTableName:tableName DicName:@"data" IdstrName:@"myId" Dic:responseObject[@"data"][@"classify"] idStr:@"page0"];
        }

        CharctResult(responseObject[@"data"][@"classify"]);
        
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
      
        DIEError *err = [[DIEError alloc]initWithError:error];
        getError(err);
       
    }];
}

@end
